import { ref, computed, watch, onMounted } from 'vue'

export type ThemeMode = 'light' | 'dark' | 'auto'

interface ThemeConfig {
  mode: ThemeMode
  primaryColor?: string
  fontSize?: 'small' | 'medium' | 'large'
  compactMode?: boolean
}

const THEME_STORAGE_KEY = 'file-history-theme'
const DEFAULT_THEME: ThemeConfig = {
  mode: 'auto',
  primaryColor: '#409eff',
  fontSize: 'medium',
  compactMode: false
}

export function useTheme() {
  const themeConfig = ref<ThemeConfig>({ ...DEFAULT_THEME })
  const systemPrefersDark = ref(false)
  
  // 计算当前实际主题
  const currentTheme = computed(() => {
    if (themeConfig.value.mode === 'auto') {
      return systemPrefersDark.value ? 'dark' : 'light'
    }
    return themeConfig.value.mode
  })
  
  // 检测系统主题偏好
  const detectSystemTheme = () => {
    if (typeof window !== 'undefined' && window.matchMedia) {
      const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
      systemPrefersDark.value = mediaQuery.matches
      
      // 监听系统主题变化
      mediaQuery.addEventListener('change', (e) => {
        systemPrefersDark.value = e.matches
      })
    }
  }
  
  // 应用主题到DOM
  const applyTheme = () => {
    const html = document.documentElement
    const body = document.body
    
    // 设置主题类
    html.classList.remove('light-theme', 'dark-theme')
    html.classList.add(`${currentTheme.value}-theme`)
    
    // 设置Element Plus主题
    if (currentTheme.value === 'dark') {
      html.classList.add('dark')
    } else {
      html.classList.remove('dark')
    }
    
    // 设置主色调
    if (themeConfig.value.primaryColor) {
      html.style.setProperty('--el-color-primary', themeConfig.value.primaryColor)
    }
    
    // 设置字体大小
    const fontSizeMap = {
      small: '13px',
      medium: '14px',
      large: '16px'
    }
    html.style.setProperty('--app-font-size', fontSizeMap[themeConfig.value.fontSize || 'medium'])
    
    // 设置紧凑模式
    if (themeConfig.value.compactMode) {
      body.classList.add('compact-mode')
    } else {
      body.classList.remove('compact-mode')
    }
  }
  
  // 保存主题配置到本地存储
  const saveTheme = () => {
    try {
      localStorage.setItem(THEME_STORAGE_KEY, JSON.stringify(themeConfig.value))
    } catch (error) {
      console.warn('无法保存主题配置:', error)
    }
  }
  
  // 从本地存储加载主题配置
  const loadTheme = () => {
    try {
      const saved = localStorage.getItem(THEME_STORAGE_KEY)
      if (saved) {
        const parsed = JSON.parse(saved)
        themeConfig.value = { ...DEFAULT_THEME, ...parsed }
      }
    } catch (error) {
      console.warn('无法加载主题配置:', error)
      themeConfig.value = { ...DEFAULT_THEME }
    }
  }
  
  // 设置主题模式
  const setThemeMode = (mode: ThemeMode) => {
    themeConfig.value.mode = mode
  }
  
  // 切换主题模式
  const toggleTheme = () => {
    const modes: ThemeMode[] = ['light', 'dark', 'auto']
    const currentIndex = modes.indexOf(themeConfig.value.mode)
    const nextIndex = (currentIndex + 1) % modes.length
    setThemeMode(modes[nextIndex])
  }
  
  // 设置主色调
  const setPrimaryColor = (color: string) => {
    themeConfig.value.primaryColor = color
  }
  
  // 设置字体大小
  const setFontSize = (size: 'small' | 'medium' | 'large') => {
    themeConfig.value.fontSize = size
  }
  
  // 切换紧凑模式
  const toggleCompactMode = () => {
    themeConfig.value.compactMode = !themeConfig.value.compactMode
  }
  
  // 重置为默认主题
  const resetTheme = () => {
    themeConfig.value = { ...DEFAULT_THEME }
  }
  
  // 监听主题配置变化
  watch(themeConfig, () => {
    applyTheme()
    saveTheme()
  }, { deep: true })
  
  // 监听系统主题变化
  watch(systemPrefersDark, () => {
    if (themeConfig.value.mode === 'auto') {
      applyTheme()
    }
  })
  
  // 初始化
  onMounted(() => {
    detectSystemTheme()
    loadTheme()
    applyTheme()
  })
  
  return {
    themeConfig: computed(() => themeConfig.value),
    currentTheme,
    systemPrefersDark: computed(() => systemPrefersDark.value),
    setThemeMode,
    toggleTheme,
    setPrimaryColor,
    setFontSize,
    toggleCompactMode,
    resetTheme,
    applyTheme
  }
}